import {
  ArrayField,
  Form,
  ObjectField,
  onFieldInputValueChange,
  onFieldMount,
  onFieldValueChange,
  onFormInit,
  onFormMount,
} from '@formily/core'
import { define, observable, action, autorun } from '@formily/reactive'
import { onBeforeUnmount, Ref, watch } from 'vue'
import { VxeTableInstance } from 'vxe-table'
import { EventEmitter } from 'events'
import { BaseDomainModel } from './domain-base'
import { ISchema } from '@formily/vue'
import { uid } from '@formily/shared'
import _ from 'lodash'
import { defineStore, Store } from 'pinia'
import { applyPatch, compare } from './json-patch'

const STATUS_NONE = ''
const STATUS_PAGE_LOADING = 'STATUS_PAGE_LOADING'
const STATUS_LOAD_ERROR = 'STATUS_LOAD_DONE'

export function createDomain() {
  const useStore = defineStore('User', {
    state: () => {
      return {
        status: '',
        schema: schema,
        list: [],
        condition: {},
        sorts: [],
        selections: { ids: [], records: [], key: 'id' },
        pager: {
          currentPage: 1,
          pageSize: 50,
          total: 0,
          sizes: [10, 20, 30, 50, 100, 500, 1000, 2000, 3000, 5000],
        },
      }
    },
    getters: {
      statusValue(state) {
        return state.status
      },
      schemaValue(state) {
        return state.schema
      },
      pagerValue(state) {
        return state.pager
      },
      listValue(state) {
        return state.list
      },
      conditionValue(state) {
        return state.condition
      },
      sortsValue(state) {
        return state.sorts
      },
      selectionsValue(state) {
        return state.selections
      },
    },
    actions: {
      setCondition(form) {
        this.condition = form
      },
      setSorts(
        sorts: { field: string; order: 'asc' | 'desc'; property: string }[]
      ) {
        this.sorts = sorts
      },
      setSelections(selections) {
        this.selections = selections
      },
      async reload() {
        this.pager.currentPage = 1
        this.query()
      },
      async loadPage({ currentPage, pageSize, params }) {
        this.pager.currentPage = currentPage
        this.pager.pageSize = pageSize
        this.query(params)
      },
      refresh() {
        this.query()
      },
      async query(params) {
        this.status = STATUS_PAGE_LOADING
        try {
          const { data, count } = await this.fetchData(params)
          this.list = data
          this.pager.total = count
        } catch (err) {
          this.status = STATUS_LOAD_ERROR
        } finally {
          this.status = STATUS_NONE
        }
      },
      patchSchema(_schema: ISchema) {
        const result = compare(schema, _schema)
        this.applyPatches(result)
      },
      applyPatches(patch: any[]) {
        let result = _.cloneDeep(schema)
        result = applyPatch(result, patch).newDocument
        this.schema = result
      },
      async fetchData(params) {
        const {
          pager: { currentPage, pageSize },
          condition,
        } = this
        return new Promise((ok, fail) => {
          setTimeout(() => {
            ok({
              data: _.times(pageSize, (index) => {
                const uuid = uid()
                return {
                  id: uuid,
                  name: uuid,
                  nickname: 'T1',
                  role: 'Develop',
                  sex: 'Man',
                  age: (currentPage - 1) * pageSize + index,
                  address: 'Shenzhen',
                }
              }),
              count: 1000,
            })
          }, 2000)
        })

      },
      handleExport() {
        console.log('handleExport')
      },
      handleImport() {
        console.log('handleImport')
      },
    },
  })
  const store = useStore()
  onBeforeUnmount(store.$dispose)
  return store
}

export const editSchema = {
  type: 'object',
  properties: {
    name: {
      title: '姓名',
      type: 'string',
      'x-decorator': 'FormItem',
      'x-component': 'Input',
    },
    nickname: {
      title: '外号',
      type: 'string',
      'x-decorator': 'FormItem',
      'x-component': 'Input',
    },
    role: {
      title: '角色',
      type: 'string',
      'x-decorator': 'FormItem',
      'x-component': 'Select',
      enum: ['Developr', 'Tester', 'Project Manager', 'Produce Manager'],
    },
    sex: {
      title: '性别',
      type: 'string',
      'x-decorator': 'FormItem',
      'x-component': 'Select',
      enum: ['Male', 'Female'],
    },
    age: {
      title: '年龄',
      type: 'number',
      'x-decorator': 'FormItem',
      'x-component': 'InputNumber',
    },
    address: {
      title: '地址',
      type: 'string',
      'x-decorator': 'FormItem',
      'x-component': 'Input',
    },
  },
}

export const schema = {
  type: 'object',
  properties: {
    gridapp: {
      type: 'array',
      'x-decorator': 'FormItem',
      'x-component': 'BFGridApp',
      'x-pattern': 'readPretty',
      'x-component-props': {},
      properties: {
        o9xhga18l8w: {
          type: 'void',
          'x-component': 'BFGridApp.Top',
          properties: {
            gap: {
              'x-component': 'div',
              'x-component-props': {
                style: {
                  height: '5px',
                  background: 'red',
                },
              },
            },
          },
          'x-reactions': [{
            fulfill: {
              state: {
                visible: "{{model.observable.status===''}}"
              }
            }
          }]
        },
        '5xdvfkldbij': {
          type: 'void',
          'x-component': 'BFGridApp.Toolbar',
          properties: {
            p1dpcmpfdf7: {
              type: 'void',
              'x-component': 'BFGridApp.Toolbar.Link',
              'x-component-props': {
                type: 'route',
                label: '新增',
                linkTo: '/create',
              },
              'x-reactions': [
                {
                  dependencies: ['gridapp.selections'],
                  fulfill: {
                    state: {
                      visible: '{{$deps[0]?.ids.length == 0}}',
                    },
                  },
                },
              ],
            },
            p1dpcmpfdf4: {
              type: 'void',
              'x-component': 'BFGridApp.Toolbar.Action',
              'x-component-props': {
                name: 'handleImport',
                label: '导入',
                service: 'actions',
              },
              'x-reactions': [
                {
                  dependencies: ['gridapp.pager'],
                  fulfill: {
                    state: {
                      visible: '{{$deps[0]?.currentPage === 1}}',
                    },
                  },
                },
              ],
            },
            wn3lyu5vjes: {
              type: 'void',
              'x-component': 'BFGridApp.Toolbar.Action',
              'x-component-props': {
                name: 'handleExport',
                label: '导出',
                service: 'actions',
              },
            },
            '2ukayo2l3uj': {
              type: 'void',
              'x-component': 'BFGridApp.Toolbar.Refresh',
              'x-component-props': {},
            },
            d46gdm4w8dd: {
              type: 'void',
              'x-component': 'BFGridApp.Toolbar.Custom',
              'x-component-props': {
                disabledColumns: ['序号'],
              },
            },
          },
        },
        afgipyowkrd: {
          type: 'void',
          'x-component': 'BFGridApp.Left',
          properties: {
            gap2: {
              'x-component': 'div',
              'x-component-props': {
                style: {
                  height: '100%',
                  width: '5px',
                  background: 'red',
                },
              },
            },
          },
        },
        a8i6wao3jjn: {
          type: 'void',
          'x-component': 'BFGridApp.Right',
          properties: {
            gap2: {
              'x-component': 'div',
              'x-component-props': {
                style: {
                  height: '100%',
                  width: '5px',
                  background: 'red',
                },
              },
            },
          },
        },
        azghs53wlsh: {
          type: 'void',
          'x-component': 'BFGridApp.Bottom',
          properties: {
            gap2: {
              'x-component': 'div',
              'x-component-props': {
                style: {
                  height: '5px',
                  background: 'red',
                },
              },
            },
          },
        },
        '35sdigtg9uw': {
          type: 'object',
          'x-component': 'BFGridApp.Form',
          'x-pattern': 'editable',
          properties: {
            hic9ho29xv7: {
              type: 'void',
              'x-component': 'Space',
              properties: {
                condition1: {
                  title: '年龄',
                  type: 'string',
                  'x-component': 'InputNumber',
                  'x-decorator': 'FormItem',
                },
                condition2: {
                  title: '姓名',
                  'x-decorator': 'FormItem',
                  'x-component': 'Input',
                },
                condition3: {
                  title: '性别',
                  'x-decorator': 'FormItem',
                  'x-component': 'Select',
                  enum: ['男', '女'],
                },
              },
            },
          },
        },
        '8l9vho3clxd': {
          type: 'array',
          'x-component': 'BFGridApp.Table',
          'x-component-props': {
            stripe: true,
            border: true,
            height: '444',
            showOverflow: true,
            sortConfig: {
              multiple: true,
            },
          },
          items: {
            type: 'object',
            properties: {
              vt86i5dap1k: {
                title: '序号',
                type: 'void',
                'x-component': 'BFGridApp.Table.Column',
                'x-component-props': {
                  type: 'seq',
                  width: 80,
                  align: 'center',
                  resizable: true,
                },
              },
              '4d2ks3g0xfi': {
                title: '单选',
                type: 'void',
                'x-component': 'BFGridApp.Table.Column',
                'x-component-props': {
                  type: 'radio',
                  width: 80,
                  align: 'center',
                  resizable: true,
                },
              },
              yw0ukhpuiob: {
                title: '多选',
                type: 'void',
                'x-component': 'BFGridApp.Table.Column',
                'x-component-props': {
                  type: 'checkbox',
                  width: 80,
                  align: 'center',
                  resizable: true,
                },
              },
              zjpijpx0r16: {
                type: 'void',
                title: '基础信息',
                'x-component': 'BFGridApp.Table.Colgroup',
                'x-component-props': {},
                properties: {
                  '7cwvj3h6xxk': {
                    type: 'void',
                    title: '基础信息分组',
                    'x-component': 'BFGridApp.Table.Colgroup',
                    properties: {
                      bxx0e1ip6zh: {
                        title: '名称',
                        type: 'void',
                        'x-component': 'BFGridApp.Table.Column',
                        'x-component-props': {
                          sortable: true,
                          width: 200,
                          resizable: true,
                        },
                        properties: {
                          name: {
                            type: 'string',
                            'x-component': 'Input',
                          },
                        },
                      },
                    },
                  },
                  ue5nxf1uvt8: {
                    title: '外号',
                    type: 'void',
                    'x-component': 'BFGridApp.Table.Column',
                    'x-component-props': {
                      width: 200,
                      resizable: true,
                      sortable: true,
                    },
                    properties: {
                      nickname: {
                        type: 'string',
                        'x-component': 'Input',
                      },
                    },
                  },
                },
              },
              vnxou64mp7s: {
                title: '角色',
                type: 'void',
                'x-component': 'BFGridApp.Table.Column',
                'x-component-props': {
                  resizable: true,
                  sortable: true,
                },
                properties: {
                  role: {
                    type: 'string',
                    'x-component': 'Input',
                  },
                },
              },
              pt3k3h71lez: {
                title: '年龄',
                type: 'void',
                'x-component': 'BFGridApp.Table.Column',
                'x-component-props': {
                  resizable: true,
                  sortable: true,
                },
                properties: {
                  age: {
                    type: 'string',
                    'x-component': 'Input',
                  },
                },
              },
            },
          },
        },
      },
    },
  },
}
